// VerifyCodeWidget.cpp
#include "VerifyCodeWidget.h"

VerifyCodeWidget::VerifyCodeWidget(QWidget *parent) : QWidget(parent), randomGenerator(QDateTime::currentMSecsSinceEpoch()) {
    // 设置初始验证码
    verifyCode = "";
    // 设置固定大小
    setFixedSize(180, 40);
}

void VerifyCodeWidget::setVerifyCode(const QString &code) {
    verifyCode = code;
    update(); // 重绘控件
}

void VerifyCodeWidget::paintEvent(QPaintEvent *event) {
    Q_UNUSED(event);
    QPainter painter(this);
    QFont font("楷体", 25, QFont::Bold, true);
    painter.setFont(font);

    // 画点: 添加随机噪点
    for (int i = 0; i < 100; i++) {
        QPen pen(QColor(randomGenerator.generate() % 256, randomGenerator.generate() % 256, randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawPoint(randomGenerator.generate() % width(), randomGenerator.generate() % height());
    }

    // 画线: 添加随机干扰线
    for (int i = 0; i < 5; i++) {
        QPen pen(QColor(randomGenerator.generate() % 256, randomGenerator.generate() % 256, randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawLine(randomGenerator.generate() % width(), randomGenerator.generate() % height(),
                         randomGenerator.generate() % width(), randomGenerator.generate() % height());
    }

    // 绘制验证码
    for (int i = 0; i < verifyCode.size(); i++) {
        QPen pen(QColor(randomGenerator.generate() % 255, randomGenerator.generate() % 255, randomGenerator.generate() % 255));
        painter.setPen(pen);
        painter.drawText(5 + 20 * i, randomGenerator.generate() % 10, 30, 30, Qt::AlignCenter, QString(verifyCode[i]));
    }
}
